package com.apes.fn.fico.reimbursement.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.hr.base.model.WorkPost;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 费用报销表
 * Created by lishikun on 2021/1/26 17:51
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Reimbursement.CONST_TABLE_NAME)
public class Reimbursement extends Model {
    public static final String CONST_TABLE_NAME = "fn_reimbursement";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "费用报销表", padding = 5, prefix = "FB%(company)%(yy)%(month)", useDateRange = true)
    @Comment("费用报销编码")
    private String id;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company;

    @Name
    @Comment("费用类别")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "fee_type_id", referencedColumnName = "id")
    private Enumeration feeType; //费用类型

    @Comment("备注")
    @Column(name = "remark", length = 250)
    private String remark;

    @Comment("报销事由")
    @Column(name = "cause", length = 250)
    private String cause;

    @Column(name = "total_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("报销合计金额")
    private double totalAmount = 0;
//
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "cost_center_id", referencedColumnName = "id")
//    @Comment("报销部门")
//    private DutyCenter dutyCenter;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "work_post_id", referencedColumnName = "id", nullable = false)
    @Comment("创建人岗位")
    private WorkPost workPost;

//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name="payment_account_id", referencedColumnName="id")
//    @Comment("付款账户")
//    private BankAccount paymentAccount;  //付款账户

    @Comment("摘要")
    @Column(name = "summary")
    private String summary;


    @Comment("付款回执")
    @Column(name = "file_address", length = 4000)
    private String fileAddress;

    @States(name = "订单状态", values = {
            @State(id = "create", name = "创建"),
            @State(id = "approve", name = "审核"),
            @State(id = "OA", name = "发起OA"),
            @State(id = "finish", name = "完成"),
            @State(id = "repeal", name = "终止"),
            @State(id = "cashier", name = "出纳"),
            @State(id = "delete", name = "删除")
    })
    @Column(name = "state", length = 10, nullable = false)
    private String state;

    @Comment("费用报销明细")
    @OneToMany(mappedBy = "reimbursement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ReimbursementItem> reimbursementItems = new ArrayList<>();

    public List<ReimbursementItem> getReimbursementItems() {
        for (ReimbursementItem item : reimbursementItems) {
            item.setReimbursement(this);
        }
        return reimbursementItems;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "repeal_id", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole repealId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "repeal_date")
    @Comment("终止日期")
    private Date repealDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "delete_id", referencedColumnName = "id")
    @Comment("删除人")
    private PartyRole deleteId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "delete_date")
    @Comment("删除日期")
    private Date deleteDate;

    @Comment("OA发起人")
    @Column(name = "OASponsor", length = 120)
    private String OASponsor;


    @Transient
    private String workPostId;  // OA使用岗位编码

    public String getWorkPostId() {
        return workPost.getId();
    }

    @Transient
    private String feeTypeName;  // OA使用费用类型名称

    public String getFeeTypeName() {
        return feeType.getDescription();
    }

    @Name
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "reimbursement_type", referencedColumnName = "id")
    private Enumeration reimbursementType; //费用报销单类型

    @Column(name = "needOA", nullable = false, columnDefinition = ApesConst.FIELD_BOOLEAN_TRUE)
    @Comment("OA流程标记")
    private Boolean needOA = false;  // OA流程

    @Comment("控制父类审批")
    @Column(name = "need_Supper_OA")
    private String needSupperOA;

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @Comment("各类费用主管")
    @Column(name = "candidates", length = 300)
    private String candidates;

    @Transient
    private String cashierOA;

    public String getCashierOA() {
        cashierOA = "1";
//        totalAmount == 0 || (reimbursementType.getId().equals("BorrowMoney") && totalAmount >= 0)
        if (this.getReimbursementItems().stream().mapToDouble(ReimbursementItem::getAwaitPayAmount).sum() == 0) {
            cashierOA = "0";
        }
        return cashierOA;
    }


    @Comment("银行流水明细")
    @OneToMany(mappedBy = "reimbursement", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<TransactionFlowItem> transactionFlowItems = new ArrayList<>();

    public List<TransactionFlowItem> getTransactionFlowItems() {
        for (TransactionFlowItem item : transactionFlowItems) {
            item.setReimbursement(this);
        }
        return transactionFlowItems;
    }

    @Column(name = "pay_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("付款金额")
    private double payAmount = 0;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "pay_id", referencedColumnName = "id")
    @Comment("付款人")
    private PartyRole payId;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "pay_date")
    @Comment("付款日期")
    private Date payDate;

    public void computeAmt() {
        payAmount = transactionFlowItems.stream().map(TransactionFlowItem::getPayAmount).reduce(Arith::add).orElse(0.0);
        if (payAmount > Math.abs(totalAmount)) {
            throw new RuntimeException("付款金额大于报销金额！请检查！");
        }
        if (payAmount == Math.abs(totalAmount)) {
            state = "finish";
        }
    }

    public void compute() {
        totalAmount = reimbursementItems.stream().map(ReimbursementItem::getAwaitPayAmount).reduce(Arith::add).orElse(0.0);
    }
}
